package org.example.flink.sink.es;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.streaming.connectors.elasticsearch7.ElasticsearchSink;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;

public class FlinkToEs {
    
    public void run() throws UnknownHostException {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStream<String> input = env.socketTextStream("", 8080);
        
//        Map<String, String> config = new HashMap<>();
//        config.put("cluster.name", "my-cluster-name");
//        //该配置表示批量写入ES时的记录条数
//        config.put("bulk.flush.max.actions", "1");

        List<HttpHost> transportAddresses = new ArrayList<>();
        transportAddresses.add(new HttpHost(InetAddress.getByName("127.0.0.1"), 9200));
        
        ElasticsearchSink<String> sink = new ElasticsearchSink.Builder<String>(transportAddresses,new ElasticsearchSinkFunction<String>() {
            /**
             *
             */
            private static final long serialVersionUID = 2936498942609389899L;
            @Override
            public void process(String element, RuntimeContext ctx, RequestIndexer indexer) {
                // TODO Auto-generated method stub
                indexer.add(createIndexRequest(element));
            }
            public IndexRequest createIndexRequest(String element) {
                Map<String, String> json = new HashMap<>();
                //将需要写入ES的字段依次添加到Map当中
                json.put("data", element);
                return Requests.indexRequest()
                        .index("my-index")
                        .source(json);
            }
        }).build();
        input.addSink(sink);
    }
    
    public static void main(String[] args) {
        
    }
}
